package com.jf.exam.security.shiro;

import com.jf.exam.pojo.data.StudentDO;
import com.jf.exam.pojo.data.TeacherDO;
import com.jf.exam.pojo.vo.ManageVO;
import com.jf.exam.service.ManageService;
import com.jf.exam.service.StudentService;
import com.jf.exam.service.TeacherService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    ManageService manageService;

    @Autowired
    StudentService studentService;

    @Autowired
    TeacherService teacherService;


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户信息，根据用户名查询账号数据
        UsernamePasswordTypeToken token = (UsernamePasswordTypeToken) authenticationToken;
        if (token.getUserType() == UsernamePasswordTypeToken.ADMIN) {
            ManageVO manager = manageService.getManageByName(token.getUsername());
            if (manager != null) {
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(manager, manager.getPassword(), getName());
                info.setCredentialsSalt(ByteSource.Util.bytes(token.getUsername().getBytes()));
                return info;
            }
        }

        if (token.getUserType() == UsernamePasswordTypeToken.STUDENT) {
            StudentDO student = studentService.getStudentByName(token.getUsername());
            if (student != null) {
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(student, student.getPassword(), getName());
                info.setCredentialsSalt(ByteSource.Util.bytes(token.getUsername().getBytes()));
                return info;
            }
        }

        if (token.getUserType() == UsernamePasswordTypeToken.TEACHER) {
            TeacherDO teacher = teacherService.getTeacherByName(token.getUsername());
            if (teacher != null) {
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(teacher, teacher.getPassword(), getName());
                info.setCredentialsSalt(ByteSource.Util.bytes(token.getUsername().getBytes()));
                return info;
            }
        }
        return null;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
